//
//  InitializesViewController.m
//  CBT
//
//  Created by Mr.Zhang on 2018/12/21.
//  Copyright © 2018 Mr.Zhang. All rights reserved.
//

#import "InitializesViewController.h"
#import "BaseLoginNavgationController.h"
#import "CBTTTabBarViewController.h"

#import "CBTNewVersionView.h"

#import "LoginManager.h"

@interface InitializesViewController ()

@property (nonatomic, strong) UIImageView *rootImageView;

@end

@implementation InitializesViewController

#pragma mark - VC Life

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.fd_prefersNavigationBarHidden = YES;

    self.rootImageView.image = [UIImage imageNamed:[self getLaunchImageName]];
    
    [self autoLogin];
}

-(void)dealloc
{
    NSLog(@" %@ will dealloc ! ",NSStringFromClass([self class]));

    if (self.rootImageView && self.rootImageView.superview != nil) {
        [self.rootImageView removeFromSuperview];
    }
}

- (NSString *)getLaunchImageName
{
    CGSize viewSize = [UIApplication sharedApplication].keyWindow.bounds.size;
    NSString *viewOrientation = @"Portrait";    //横屏请设置成 @"Landscape"
    NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    for (NSDictionary* dict in imagesDict)
    {
        CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
        
        if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
        {
            return dict[@"UILaunchImageName"];
        }
    }
    return @"";
}

#pragma mark - 检查更新

-(void)checkOutAppVersion
{
    [NetWork requestWithURL:Network_CheckIOSUpdate params:nil httpMethod:@"GET" finishedBlock:^(NSURLSessionDataTask *task, id  _Nullable result) {
        
        if ([result[@"code"]intValue] == 100) {
            
            if(![[result[@"data"] allKeys] containsObject:@"version_code"]){
                return;
            }
            
            NSString *localVerson =  [[[NSBundle mainBundle] infoDictionary]objectForKey:@"CFBundleShortVersionString"];
            NSString *nowVerson = [result[@"data"]objectForKey:@"version_code"];
            BOOL isUpData = [nowVerson compare:localVerson options:NSNumericSearch] == NSOrderedDescending;
            if (isUpData) {
                
                UIView *bgView = [[UIView alloc]initWithFrame:[UIApplication sharedApplication].keyWindow.bounds];
                bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
                [[UIApplication sharedApplication].keyWindow addSubview:bgView];
                
                CBTNewVersionView *versionView = [[[NSBundle mainBundle] loadNibNamed:@"CBTNewVersionView" owner:nil options:nil]objectAtIndex:0];
                versionView.frame = CGRectMake(0, 0, ScreenNarrowSide - 30, 290);
                [versionView showVersionViewWithDic:result];
                
                NSString *updateAddr = [result[@"data"]objectForKey:@"url"];
                [versionView setUpDataClickBlock:^(NSInteger type,CBTNewVersionView *view){
                    if (type == 2) {
                        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:updateAddr] options:@{} completionHandler:^(BOOL success) {}];
                    }
                    else {
                        [bgView removeFromSuperview];
                        [view removeFromSuperview];
                    }
                }];
                versionView.center = [UIApplication sharedApplication].keyWindow.center;
                [[UIApplication sharedApplication].keyWindow addSubview:versionView];
                [versionView bringSubviewToFront:[UIApplication sharedApplication].keyWindow];
            }
        }
    } failureBlock:^(NSURLSessionDataTask *task, NSError *error) {
    }];
}

#pragma mark - 自动登录
- (void)autoLogin
{
    @weak(self)
    if ([CBTLocalUserManager sharedInstance].isLogIn){
        NSString *area = [[NSUserDefaults standardUserDefaults] objectForKey:@"area"];

        [LoginManager phoneaAndEmailLoginWithID:[NSString isBlankString:[CBTLocalUserManager sharedInstance].userPhone] ? [CBTLocalUserManager sharedInstance].userEmail : [CBTLocalUserManager sharedInstance].userPhone isPhone:![NSString isBlankString:[CBTLocalUserManager sharedInstance].userPhone]  pwd:HEFANTV_UserPassWord area:area block:^(id data, HttpRequestResult result, NSString *msg) {
            if (result == kHttpRequestResultNormal) {
               
                [[NSUserDefaults standardUserDefaults]setObject:[data[@"data"]objectForKey:@"token"] forKey:HEFANTV_TOKEN];
                [[NSUserDefaults standardUserDefaults]synchronize];
                
                [[CBTLocalUserManager sharedInstance] saveALLUserInfoDic:data];
                
                if (![NSString isBlankString:[data[@"data"]objectForKey:@"picUrl"]]) {
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        [CBTImageTools saveUserImageWithImage:[UIImage sd_animatedGIFWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",kBaseURL_PICSTATIC,[data[@"data"]objectForKey:@"picUrl"]]]]] imageName:[NSString stringWithFormat:@"%@",[data[@"data"]objectForKey:@"picUrl"]] userID:[data[@"data"]objectForKey:@"userId"]];
                    });
                }
                
                
                if (self_weak_.rootImageView && self_weak_.rootImageView.superview != nil) {
                    [self_weak_.rootImageView removeFromSuperview];
                }
                
                UIViewController *rootVC = [CBTTTabBarViewController new];
                rootVC.view.backgroundColor = [UIColor whiteColor];
                [UIAPPLICATION restoreRootViewController:rootVC];
                
               
            }else{
                UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
                BaseLoginNavgationController *nav = [story instantiateViewControllerWithIdentifier:@"loginNav"];
                [UIAPPLICATION restoreRootViewController:nav];
            }
            [self_weak_ checkOutAppVersion];
        }];
    }else{
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        BaseLoginNavgationController *nav = [story instantiateViewControllerWithIdentifier:@"loginNav"];
        [UIAPPLICATION restoreRootViewController:nav];
        [self_weak_ checkOutAppVersion];
    }
}

#pragma mark - Lazy

- (UIImageView *)rootImageView
{
    if (!_rootImageView) {
        _rootImageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
        [self.view addSubview:_rootImageView];
    }
    return _rootImageView;
}

@end
